<script setup lang="ts">
import { request } from '@/api' // 使用别名 @ 来指向 src 目录
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant'
import { onMounted, ref } from 'vue'
import base64ToBlob from 'b64-to-blob'

// 1. 修改头像
// 1.1 控制修改头像弹层的显示/隐藏，是否显示 拍照，相册交互弹窗
/**
 * 1.拍照，或者相册，获取选择的图片信息
 * 2.根据接口文档提交数据
 * 3，本地更新投邮箱信息即可
 */
const showAvatarSheet = ref(false)
// 1.2 打开相册/相机
const onSelectAvatar = async (item: ActionSheetAction, i: number) => {
  if (i === 0) {
    // 相册上传
    // console.log('相册上传')
    const data = await mk.pickerPhoto()
    await onUpdateAvatar(data)
  } else if (i === 1) {
    // 拍照上传
    // console.log('拍照上传')
    const data = await mk.pickerCamera()
    await onUpdateAvatar(data)
  }
}
// 1.3 头像上传
const onUpdateAvatar = async (data: string) => {
  try {
    showAvatarSheet.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    // base64转 二进制
    const image = base64ToBlob(data, 'image/jpeg')
    // 创建一个转载数据的formData对象
    const fd = new FormData()
    // 追加数据
    // file key
    // img数据
    // 参数3名字
    fd.append('file', image, Date.now() + '.jpeg')
    // 调用上传接口，根据接口文档设置地址和方法，formData 设置到参数2即可
    const res = await request.post<MkResponse<{ avatar: string }>>('member/profile/avatar', fd)
    // 修改页面显示
    profile.value.avatar = URL.createObjectURL(image)
    // 获取保存在鸿蒙缓存中用户信息
    const user = mk.queryUser()
    // 修改用户信息的头像 为上传成功之后的头像
    user.avatar = res.data.result.avatar
    // 更新鸿蒙端的头像
    mk.updateUser(user)
    showToast({ message: '上传成功' })
  } catch (err) {
    showToast({ message: '上传失败' })
  }
}
// 2. 选择生日日期
const showBirthdayPopup = ref(false)
const onChangeBirthday = () => {
  // console.log(currentDate.value)
  showBirthdayPopup.value = false
  profile.value.birthday = currentDate.value.join('-')
}
const currentDate = ref(['2000', '02', '03'])

// 3. 选择所在地
const areaColumns = ref<AreaColumns>()
const showLocationPopup = ref(false)
onMounted(async () => {
  const data = await mk.getAreaColumns()
  areaColumns.value = data
  console.log(data)
})
const onSelectedLocation = (data: { selectedValues: any[]; selectedOptions: any }) => {
  showLocationPopup.value = false
  console.log(data)
  // console.log(data.selectedOptions)
  const arr = data.selectedOptions.map((v: any) => {
    return v.text
  })
  // 修改页面渲染的省市区
  profile.value.fullLocation = arr.join(' ')

  // 修改提交数据中的 省市区
  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]
}

// 4. 选择职业
// 职业列表
const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' },
]
// 是否显示
const showProfessionPopup = ref(false)
// 点击提交
const onChangeProfession = (data: { selectedValues: string[] }) => {
  // console.log(data)
  showProfessionPopup.value = false
  profile.value.profession = data.selectedValues.join('')
}

// 获取用户信息
const profile = ref<ProfileInfo>({} as ProfileInfo)
onMounted(async () => {
  showLoadingToast({ message: '加载中...', duration: 0, forbidClick: true })
  const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
  closeToast()
  profile.value = res.data.result
  // 生日
  currentDate.value = profile.value.birthday.split('-')
})

// 保存资料
const loading = ref(false)
const onSubmit = async () => {
  console.log(profile.value)
  // mk.vibrator()
  loading.value = true
  const res = await request.put<MkResponse<ProfileInfo>>('member/profile', profile.value)
  console.log(res)
  loading.value = false
  mk.updateUser(res.data.result)
  showToast({ message: '保存成功' })
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        round
        width="100"
        height="100"
        class="avatar-img"
        src="https://foruda.gitee.com/avatar/1716533299289369832/5539886_yjh8866_1716533299.png"
        @click="showAvatarSheet = true"
      >
      </van-image>
      <!-- 选择拍照 还是相册 -->
      <van-action-sheet
        v-model:show="showAvatarSheet"
        :actions="[{ name: '相册' }, { name: '拍照' }]"
        @select="onSelectAvatar"
        cancel-text="取消"
        :style="{ paddingBottom: '20px' }"
      ></van-action-sheet>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>
    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field v-model="profile.account" label="账号" readonly></van-field>
      <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field
        @click="showBirthdayPopup = true"
        label="生日"
        readonly
        placeholder="请选择日期"
        v-model="profile.birthday"
      ></van-field>
      <van-field
        label="所在地"
        readonly
        placeholder="选择省市区"
        @click="showLocationPopup = true"
        v-model="profile.fullLocation"
      ></van-field>

      <!-- 选择职业弹层 -->
      <van-field
        label="职业"
        readonly
        placeholder="请选择职业"
        @click="showProfessionPopup = true"
        v-model="profile.profession"
      ></van-field>
    </van-cell-group>

    <div class="submit">
      <van-button @click="onSubmit()" round block type="primary"> 保存资料 </van-button>
    </div>
    <!-- 选择生日弹层 -->
    <van-popup v-model:show="showBirthdayPopup" round position="bottom">
      <van-date-picker
        v-model="currentDate"
        title="选择日期"
        @cancel="showBirthdayPopup = false"
        @confirm="onChangeBirthday"
        :min-date="new Date('1980-01-01')"
      />
    </van-popup>

    <!-- 选择所在地弹层 -->
    <van-popup v-model:show="showLocationPopup" round position="bottom">
      <van-area
        :area-list="areaColumns"
        title="选择省市区"
        @confirm="onSelectedLocation"
        @cancel="showLocationPopup = false"
      ></van-area>
    </van-popup>

    <!-- 打开选择职业弹层 -->
    <van-popup v-model:show="showProfessionPopup" round position="bottom">
      <van-picker
        :columns="columns"
        @confirm="onChangeProfession"
        @cancel="showProfessionPopup = false"
      />
    </van-popup>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
